<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Order;

use App\Models\Amazon\AmazonOrder;
use App\Models\Amazon\AmazonOrderAddress;
use App\Models\Amazon\AmazonOrderAddressOld;
use App\Models\Amazon\AmazonOrderItem;
use App\Models\Amazon\AmazonOrderItemOld;
use App\Models\Amazon\AmazonOrderOld;
use App\Models\Amazon\AmazonSkuName;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductAmazonSku;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AmazonAjax {

    public function orderExport(){
        return view('order.amazon.export');
    }

    public function doOrderExport($param){
        if(isset($param['address'])&&$param['address'] == 1){
            $head = ['amazon-order-id','purchase-date','product-name','sku','sku-name','asin','item-price','sales-channel','ship-city','ship-state','ship-postal-code','ship-country'];
            $type = 'withAddress';
        }else{
            $head = ['购买日期','订单号','商城','渠道','状态','账号','SKU','SKU名称','ASIN', '数量','货币','售价'];
            $type = 'withoutAddress';
        }

        //ordrs_new
        $orders = AmazonOrder::query()
            ->where('purchase_date','>=',$param['start_date'].' 00:00:00')
            ->where('purchase_date','<=',$param['end_date'].' 23:59:59')
            ->select('id', 'amazon_order_id', 'purchase_date', 'marketplace_id', 'sales_channel', 'order_status', 'created_at', 'updated_at');
        //ordrs_old
        $query = AmazonOrderOld::query()
            ->where('purchase_date','>=',$param['start_date'].' 00:00:00')
            ->where('purchase_date','<=',$param['end_date'].' 23:59:59')
            ->select('id', 'amazon_order_id', 'purchase_date', 'marketplace_id', 'sales_channel', 'order_status', 'created_at', 'updated_at')
            ->union($orders);

        if(isset($param['country_id'])&&$param['country_id']){
            $marketplaceIds = AmazonCountry::query()->whereIn('country_id',$param['country_id'])->pluck('marketplace_id');
            $query->whereIn('marketplace_id',$marketplaceIds);
        }
        if(isset($param['account_id'])&&$param['account_id']){
            $accountId = $param['account_id'];
            $query->whereHas('items', function ($query) use($accountId){
                $query->where('account_id',$accountId);
            });
        }
        $this->_exeDownload($head,$query,$type);
    }

    private function _exeDownload($head,$query,$type){
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="订单导出.csv"',
        ]);
        $response->setCallback(function () use ($head, $query, $type) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(500, function ($re) use ($fp,$type){
                $data = $this->{'__'.$type}($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    /**
     * 关联地址（包含地址）
     * @param $re
     * @return \Generator
     */
    private function __withAddress($re){
        foreach ($re as $item){

            if (strtotime($item->purchase_date) >= strtotime('2023-12-01 00:00:00')) {
                $item->items = AmazonOrderItem::query()->where('amazon_order_id',$item->amazon_order_id)->get();
                $item->address = AmazonOrderAddress::query()->where('amazon_order_id',$item->amazon_order_id)->first();
            }else{
                $item->items = AmazonOrderItemOld::query()->where('amazon_order_id',$item->amazon_order_id)->get();
                $item->address = AmazonOrderAddressOld::query()->where('amazon_order_id',$item->amazon_order_id)->first();
            }

            foreach ($item->items as $row){
                $countryId = AmazonCountry::getCountryIdByMarketplaceId($item->marketplace_id);
                $amazonSku = ProductAmazonSku::query()->where([
                    'seller_sku' => $row->sku,
                    'country_id' => $countryId
                ])->first();
                $skuName = $amazonSku->sku->psku_cn ?? '';

                $temp = [];
                $temp['amazon_order_id'] = $item->amazon_order_id;
                $temp['purchase_date'] = $item->purchase_date;
                $temp['product_name'] = AmazonSkuName::getName($row->sku);
                $temp['sku'] = "".$row->sku;
                $temp['sku_name'] = $skuName;
                $temp['asin'] = $row->asin;
                $temp['price'] = $row->price;
                $temp['sales_channel'] = $item->sales_channel;
                $temp['city'] = $item->address->city ?? '';
                $temp['state'] = $item->address->state ?? '';
                $temp['postal_code'] = $item->address->postal_code ?? '';
                $temp['country'] = $item->address->country ?? '';
                yield $temp;
            }
        }
    }

    /**
     * 不关联地址（不包含地址）
     * @param $re
     * @return \Generator
     */
    private function __withoutAddress($re){
        foreach ($re as $item){

            if (strtotime($item->purchase_date) >= strtotime('2023-12-01 00:00:00')) {
                $item->items = AmazonOrderItem::query()->where('amazon_order_id',$item->amazon_order_id)->get();
            }else{
                $item->items = AmazonOrderItemOld::query()->where('amazon_order_id',$item->amazon_order_id)->get();
            }

            foreach ($item->items as $row){
                $countryId = AmazonCountry::getCountryIdByMarketplaceId($item->marketplace_id);
                $amazonSku = ProductAmazonSku::query()->where([
                    'seller_sku' => $row->sku,
                    'country_id' => $countryId
                ])->first();
                $skuName = $amazonSku->sku->psku_cn ?? '';

                $temp = [];
                $temp['purchase_date'] = $item->purchase_date;
                $temp['amazon_order_id'] = $item->amazon_order_id;
                $temp['marketplace_id'] = $item->marketplace_id;
                $temp['sales_channel'] = $item->sales_channel;
                $temp['order_status'] = AmazonOrder::$_orderStatus[$item->order_status];
                $temp['account_id'] = AmazonAccount::getAccountById($row->account_id);
                $temp['sku'] = "".$row->sku;
                $temp['sku_name'] = $skuName;
                $temp['asin'] = $row->asin;
                $temp['quantity'] = $row->quantity;
                $temp['currency'] = $row->currency;
                $temp['price'] = $row->price;
                yield $temp;
            }
        }
    }

    //public function syncOrder($param){
    //    try{
    //        Artisan::call('get:order',
    //            ['orderId' => explode(',',$param['amazonOrderId']),
    //                '--areaId' => $param['areaId']]);
    //        return response()->json(['status' => true, 'message' => '同步成功！']);
    //    }catch (\Exception $e){
    //        report($e);
    //        return response()->json(['status' => false, 'message' => '系统错误']);
    //    }
    //}

}
